<template>
  <div class="flldata login">
    <div class="companyname font400 content3 color3">所在公司：{{ data.companyName }}</div>
    <div class="underline" style="width: 120px">
      <span class="title1 color1 zIndex fontBold">活动报名</span>
    </div>
    <div class="login_content">
      <div class="content">
        <div class="contentInfo">
          <div class="contentInfoBox flex justify_between flex_column">
            <p class="font400 content3 color3">
              活动 / {{ route.query.title }}
            </p>
            <p class="font400 content2 color6">
              {{ route.query.deadline }}
            </p>
          </div>
        </div>
        <!-- <div class="flex justify_between align_center">
          <p class="font400 content3 color3">
            报名人数
          </p>
          <van-stepper
            v-model="value"
            input-width="40px"
            button-size="32px"
          />
        </div> -->
        <div v-for="(item, ind) in value" :key="ind">
          <div class="underline" style="width: 120px">
            <span class="title1 color1 zIndex fontBold">参与人{{ ind + 1 }}</span>
          </div>
          <div class="login_field">
            <van-cell-group>
              <van-field v-if="route.query.activeType == 1" v-model="form[ind].purposeTitle" is-link readonly
                name="picker" @click="openOnConfirm(ind)">
                <template #left-icon>
                  <span class="content3 font400 color3 leftw"><span style=" color: #f8494d" class="reqIcon">*</span>用途</span>
                  <span class="line content3 font400 color3">|</span>
                </template>
              </van-field>
              <van-popup v-model:show="showUse" position='bottom'>
                <van-picker :columns="useList" @confirm="onConfirm" @cancel="showUse = false" />
              </van-popup>
              <van-field v-if="form[ind].purposeTitle == '其它（请填写）'" v-model="form[ind].other" center>
                <template #left-icon>
                  <span class="content3 font400 color3 leftw">其他用途</span>
                  <span class="line content3 font400 color3">|</span>
                </template>
              </van-field>
              <van-field v-model="form[ind].username" center>
                <template #left-icon>
                  <span class="content3 font400 color3 leftw"><span style=" color: #f8494d" class="reqIcon">*</span>姓名</span>
                  <span class="line content3 font400 color3">|</span>
                </template>
              </van-field>
              <van-field v-if="route.query.activeType == 1" v-model="form[ind].card_number" center>
                <template #left-icon>
                  <span class="content3 font400 color3 leftw"><span style=" color: #f8494d" class="reqIcon">*</span>身份证号</span>
                  <span class="line content3 font400 color3">|</span>
                </template>
              </van-field>
              <van-field v-model="form[ind].phone" center>
                <template #left-icon>
                  <span class="content3 font400 color3 leftw"><span style=" color: #f8494d" class="reqIcon">*</span>电话</span>
                  <span class="line content3 font400 color3">|</span>
                </template>
              </van-field>
              <van-field v-if="false" v-model="form[ind].company" center>
                <template #left-icon>
                  <span class="content3 font400 color3 leftw">公司</span>
                  <span class="line content3 font400 color3">|</span>
                </template>
              </van-field>
              <van-field v-model="form[ind].job" center>
                <template #left-icon>
                  <span class="content3 font400 color3 leftw"><span style=" color: #f8494d" class="reqIcon">*</span>职位</span>
                  <span class="line content3 font400 color3">|</span>
                </template>
              </van-field>
              <van-field v-if="route.query.activeType == 1" center @click="getIndex(ind)" readonly>
                <template #left-icon>
                  <span class="content3 font400 color3 leftw"><span style=" color: #f8494d" class="reqIcon">*</span>大1寸证件照</span>
                  <span class="line content3 font400 color3">|</span>
                </template>
                <template #button>
                  <div class="flex align_center">
                    <img v-if="form[ind].image" class="uploaded-img" :src="form[ind].image">
                    <van-uploader :after-read="onRead" multiple :max-count="1" :disabled="uploadDisabled">
                      <van-button size="small" type="primary" color="#12142E" class="setBnt"
                        :loading="form[ind].uploadLoading">
                        {{ ind !== index && uploadDisabled ? "等待上传" : form[ind].uploadText || '上传完毕' }}
                      </van-button>
                    </van-uploader>
                  </div>
                </template>
              </van-field>

              <div class="new_field" v-for="(nItem, nIndex) in form[ind].formParam" :key="nIndex">
                <p><span v-if="nItem.is_required == 1" class="reqIcon">*</span>{{ nItem.content }}</p>
                <div v-if="nItem.type == 1">
                  <van-field :key="ind" center v-model="nItem.value" />
                </div>
                <div v-if="nItem.type == 2">
                  <van-field center rows="2" autosize type="textarea" v-model="nItem.value" />
                </div>
                <div v-if="nItem.type == 3">
                  <van-field center>
                    <template #input>
                      <van-radio-group v-model="nItem.value" @click="handleTest(ind)">
                        <van-radio v-for="(rItem, rInd) in nItem.option" :key="rInd" :name="rItem.value">
                          {{ rItem.label }}
                        </van-radio>
                      </van-radio-group>
                    </template>
                  </van-field>
                </div>
                <div v-if="nItem.type == 4">
                  <van-field center>
                    <template #input>
                      <van-checkbox-group v-model="nItem.value">
                        <van-checkbox shape="square" v-for="(rItem, rInd) in nItem.option" :key="rInd"
                          :name="rItem.value">
                          {{ rItem.label }}
                        </van-checkbox>
                      </van-checkbox-group>
                    </template>
                  </van-field>
                </div>
                <div style="margin-bottom: 10px;padding-bottom: 10px;" v-if="nItem.type == 5">
                  <van-uploader v-model="nItem.value" :max-count="1" :after-read="(e) => onReadAct(e, ind, nIndex)" />
                  <!-- <van-field
                    style="width: 92%"
                    center
                    readonly
                  >
                    <template #button>
                      <div class="flex align_center">
                        <img
                          v-if="nItem.value"
                          class="uploaded-file"
                          :src="nItem.value"
                        >
                        <van-uploader
                          :after-read="(e) => onReadAct(e, ind, nIndex)"
                          multiple
                          :max-count="1"
                          :disabled="uploadDisabled"
                        >
                          <van-button
                            size="small"
                            type="primary"
                            color="#12142E"
                            class="setBnt"
                            :loading="nItem.loading"
                          >
                            上传
                          </van-button>
                        </van-uploader>
                      </div>
                    </template>
                  </van-field> -->
                </div>
              </div>
            </van-cell-group>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="fexd_footer">
    <div class="footer_btn flex align_center justify_between">
      <div @click="back" class="btn_item cancle font400 content3 color4">
        返回
      </div>
      <div @click="submit" class="btn_item agree font400 content3 color4">
        提交
      </div>
    </div>
  </div>
  <van-dialog v-model:show="showQrCode" @confirm="closeQrCode" title="报名成功" :close-on-click-overlay="false"
    confirm-button-color="#FF7A1F">
    <div class="Scan">
      <p class="font400 content3 color3">
        长按识别二维码，进入本期活动微信群
      </p>
      <img :src="qrCodeUrl">
    </div>
  </van-dialog>

  <van-dialog v-model:show="showQrCode2"  :title="title" :close-on-click-overlay="false"
    confirm-button-color="#FF7A1F">
  </van-dialog>
</template>

<script setup lang="ts">
import _ from 'lodash'
import axios from 'axios'
import { getToken } from '@/service/cookie'
import { Toast, Dialog } from 'vant'
import { addActivity, activityUserList, getActivityQrcode, writecontent, getUserNowCompanyInfo } from '@/api/index'
// import { throttle } from '@/util/index'
import { ref, onMounted, onUnmounted, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'
const router = useRouter()
const route = useRoute()
const store = useStore()
const value: any = ref(Number(route.query.sign_num) || 1)
const index: any = ref(0)
const showUse: any = ref(false)
const showQrCode: any = ref(false)
const showQrCode2: any = ref(false)
const qrCodeUrl: any = ref('')
const uploadDisabled: any = ref(0)
const useList: any = ref(['网签签章', '营销人员', '财务人员', '其它（请填写）'])
const addFormList = ref([] as any)
// const inputType = {
//   1: 'text',
//   2: 'textarea'
// }

// const getUserInfo = async () => {
//   await store.dispatch('fetchUserInfo')
// }

// getUserInfo()

const data = reactive({
  companyName: ''
})

const form: any = ref([
  {
    username: store.state.userInfo.username,
    name: '',
    phone: store.state.userInfo.phone,
    // company: '',
    // 用途
    purpose: '',
    purposeTitle: '',
    other: '',
    job: store.state.userInfo.job,
    card_number: store.state.userInfo.card_number,
    image: store.state.userInfo.image,
    uploadLoading: false,
    uploadText: '上传',
    // 新增的字段
    formParam: [] as any
  }
])

for (let index = 1; index < Number(route.query.sign_num); index++) {
  form.value.push({
    username: '',
    name: '',
    purpose: '',
    purposeTitle: '',
    other: '',
    phone: '',
    // company: '',
    job: '',
    image: '',
    uploadLoading: false,
    uploadText: '上传',
    // 新增的字段
    formParam: [] as any
  })
}

const handleTest = (inde: any) => {
  console.log('9090', inde)
}

onMounted(() => {
  document.body.style.background = '#fff'
  // if (window.location.href.indexOf('#reloaded') === -1) {
  //   window.location.href = window.location.href + '#reloaded'
  //   window.location.reload()
  // }
})

onUnmounted(() => {
  document.body.style.background = '#f7f7f7'
})

const getUserNowCompany = () => {
  getUserNowCompanyInfo().then((res: any) => {
    console.log('res', res)
    data.companyName = res.company
  })
}

getUserNowCompany()

const openOnConfirm = (ind: any) => {
  showUse.value = true
  index.value = ind
}

const getWriteContent = () => {
  writecontent({ activity_id: route.query.active_id }).then((res: any) => {
    form.value.forEach((_, ind: any) => {
      form.value[ind].formParam = JSON.parse(JSON.stringify(res.list))
    })
    addFormList.value = res.list
  })
}

getWriteContent()

const closeQrCode = () => {
  showQrCode.value = false
  router.replace({
    path: '/find/activity',
    query: { id: route.query.active_id, success: 1 }
  })
}
console.log('route', window.location)

const onConfirm = (e: any, purIndex: number) => {
  form.value[index.value].purposeTitle = e
  form.value[index.value].purpose = purIndex + 1
  showUse.value = false
}

const getList = async () => {
  try {
    if (sessionStorage.getItem('user_ids')) {
      const { user_list }: any = await activityUserList({ active_id: route.query.active_id, user_ids: sessionStorage.getItem('user_ids') })
      user_list.forEach((item: any) => {
        item.purposeTitle = useList.value[Number(item.purpose) - 1]
        item.purpose = item.purpose || '0'
        item.formParam && item.formParam.forEach((fItem: any) => {
          if (fItem.type === 4) {
            fItem.value = fItem.value.split(',').map((nItem: any) => nItem)
          }
          if (fItem.type === 5) {
            fItem.value = [{ url: fItem.value }]
          }
        })
      })
      console.log('user_list', user_list)
      form.value = user_list
    }
  } catch (error: any) {
    Toast(error.message)
  }
}
getList()

console.log('store.state.userInfo', form.value)

const back = () => {
  if (store.state.from.path !== '/') {
    router.back()
  } else {
    router.replace('/')
  }
}

const getIndex = async (i: any) => {
  index.value = Number(i)
}

const onReadAct = async (file: any, ind: number, nIndex: number) => {
  console.log('file', file)
  console.log('ind', ind)
  console.log('nIndex', form.value[ind].formParam[nIndex])
  form.value[ind].formParam[nIndex].loading = true
  form.value[ind].formParam[nIndex].btnText = '上传中'
  const formDataFile = new FormData()
  formDataFile.append('file', file.file)
  axios({
    method: 'post',
    url: import.meta.env.VITE_API_BASEURL + 'v1/common/upload',
    data: formDataFile,
    headers: {
      'Content-Type': 'multipart/form-data',
      authorization: getToken('token')
    }
  }).then((res: any) => {
    form.value[ind].formParam[nIndex].value = [{ url: res.data.data.url }]
    form.value[ind].formParam[nIndex].loading = false
    form.value[ind].formParam[nIndex].btnText = '上传完毕'
    // uploadDisabled.value = false
    // form.value[index.value].uploadText = '上传完毕'
    // form.value[index.value].uploadLoading = false
    // form.value[index.value].image = res.data.data.url
    // image.value.push(res.data.data.url)
  })
  // if (form.value[ind].formParam.value[nIndex]?.type === 5) {
  // }
}

const onRead = async (file: any) => {
  // uploadText.value = '上传中'
  uploadDisabled.value = true
  form.value[index.value].uploadText = '上传中'
  form.value[index.value].uploadLoading = true
  console.log(index.value, 999)
  if (file.length > 1) {
    file.forEach(async (item: any) => {
      const formData = new FormData()
      formData.append('file', item.file)
      uploadFile(formData)
    })
  } else {
    const formData = new FormData()
    formData.append('file', file.file)
    uploadFile(formData)
  }
}

const uploadFile = async (formData: any) => {
  axios({
    method: 'post',
    url: import.meta.env.VITE_API_BASEURL + 'v1/common/upload',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data',
      authorization: getToken('token')
    }
  }).then((res: any) => {
    uploadDisabled.value = false
    form.value[index.value].uploadText = '上传完毕'
    form.value[index.value].uploadLoading = false
    form.value[index.value].image = res.data.data.url
    // image.value.push(res.data.data.url)
  })
}

const title = ref('')

const submit = _.throttle(async () => {
  try {
    form.value.forEach((item: any) => {
      item.params = item.formParam.map((iitem: any) => ({
        id: iitem.id,
        value: iitem.type === 4 ? iitem.value?.join(',') || '' : (iitem.type === 5 ? iitem.value && iitem.value[0].url : iitem.value) || ''
      }))
    })
    const res: any = await addActivity({
      price_id: route.query.price_id,
      sign_users: JSON.stringify(form.value),
      active_id: route.query.active_id
    })
    if (res?.code && res.code === 203) {
      title.value = res.data.msg
      showQrCode2.value = true
      return
    }
    if (res.user_ids) {
      sessionStorage.setItem('user_ids', res.user_ids)
      console.log(res.price_id, 'res.user_ids')
      router.push({
        path: '/userCenter/order',
        query: {
          price_id: res.price_id,
          pay_type: 2,
          pay_method: 0,
          paid_id: route.query.active_id,
          user_ids: JSON.stringify(res.user_ids),
          active_id: route.query.active_id
        }
      })
    } else {
      // 报名成功打开二维码，提醒扫码加群
      getActivityQrcode({ activity_id: route.query.id || route.query.active_id }).then((res: any) => {
        if (res.url) {
          showQrCode.value = true
          qrCodeUrl.value = res.url
        } else {
          Dialog.alert({
            message: '报名成功',
            confirmButtonColor: '#FF7A1F'
          }).then(() => {
            router.replace({
              path: '/find/activity',
              query: { id: route.query.active_id, success: 1 }
            })
          })
        }
      })
    }
  } catch (error: any) {
    Toast(error.message)
  }
}, 1000)

</script>

<style lang="less" scoped>
::v-deep .van-uploader__upload {
  background-color: #fff;
  margin: 10px 0 0 10px;
}

::v-deep .van-uploader__preview-image {
  margin: 10px 0 0 10px;
}

.companyname {
  padding-bottom: 10px;
}

.flldata {
  padding: 0 30px 80px;
  margin-top: 40px;

  .login_content {
    margin-top: 20px;

    .contentInfo {
      width: 100%;
      background: #f7f7f7;
      border-radius: 10px;
      margin: 20px 0;

      .contentInfoBox {
        padding: 15px;

        p:last-child {
          margin-top: 25px;
        }
      }
    }

    .login_field {
      margin-top: 20px;

      .new_field {
        p {
          margin-left: 15px;
          font-size: 15px;
        }

        .reqIcon {
          color: #f8494d;
        }

        background: #f7f7f7;
        padding-top: 15px;
        border-radius: 5px;
      }

      ::v-deep .van-checkbox,
      ::v-deep .van-radio {
        margin-bottom: 10px;
      }
    }
  }

  .leftw {
    width: 90px;
    display: inline-block;
  }

  // .line {
  //     margin: 0 30px;
  // }
  .setBnt {
    width: 98px;
    height: 30px;
    background: #12142e;
    border-radius: 5px;
    font-size: 14px;
    font-weight: 400;
  }
}

.uploaded-file {
  height: 30px;
  width: 40vw;
  margin-right: 10px;
  object-fit: cover;
}

.uploaded-img {
  width: 60px;
  height: 30px;
  object-fit: cover;
  margin-right: 10px;
}

.fexd_footer {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 70px;
  background-color: #fff;
  box-shadow: 0px 2px 12px 2px rgba(22, 12, 6, 0.09);
  z-index: 10;

  .footer_btn {
    padding: 0 30px;
    height: 100%;

    .agree {
      width: 140px;
      height: 44px;
      background: #ff7a1f;
      border-radius: 5px;
      text-align: center;
      line-height: 44px;
    }

    .cancle {
      width: 140px;
      height: 44px;
      background: #85898c;
      border-radius: 5px;
      text-align: center;
      line-height: 44px;
    }
  }
}

.Scan {
  p {
    width: 190px;
    margin: 18px auto;
    text-align: center;
    line-height: 20px;
  }

  img {
    width: 120px;
    height: 120px;
    object-fit: contain;
    margin: 0 auto 20px auto;
  }
}

@media (min-width: 750px) {

  ::v-deep .van-uploader__upload {
    background-color: #fff;
    margin: 10px 0 0 10px;
  }

  ::v-deep .van-uploader__preview-image {
    margin: 10px 0 0 10px;
  }

  .flldata {
    padding: 0 30px 80px;
    margin-top: 40px;

    .login_content {
      margin-top: 20px;

      .contentInfo {
        width: 100%;
        background: #f7f7f7;
        border-radius: 10px;
        margin: 20px 0;

        .contentInfoBox {
          padding: 15px;

          p:last-child {
            margin-top: 25px;
          }
        }
      }

      .login_field {
        margin-top: 20px;

        .new_field {
          p {
            margin-left: 15px;
            font-size: 15px;
          }

          background: #f7f7f7;
          padding-top: 15px;
          border-radius: 5px;
        }

        ::v-deep .van-checkbox,
        ::v-deep .van-radio {
          margin-bottom: 10px;
        }
      }
    }

    .leftw {
      width: 90px;
      display: inline-block;
    }

    // .line {
    //     margin: 0 30px;
    // }
    .setBnt {
      width: 98px;
      height: 30px;
      background: #12142e;
      border-radius: 5px;
      font-size: 14px;
      font-weight: 400;
    }
  }

  .Scan {
    p {
      width: 190px;
      margin: 18px auto;
      text-align: center;
      line-height: 20px;
    }

    img {
      width: 95px;
      height: 95px;
      object-fit: contain;
      margin: 0 auto;
    }
  }

  .uploaded-file {
    height: 30px;
    width: 40vw;
    margin-right: 10px;
    object-fit: cover;
  }

  .uploaded-img {
    width: 60px;
    height: 30px;
    object-fit: cover;
    margin-right: 10px;
  }

  .fexd_footer {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 70px;
    background-color: #fff;
    box-shadow: 0px 2px 12px 2px rgba(22, 12, 6, 0.09);
    z-index: 10;

    .footer_btn {
      padding: 0 30px;
      height: 100%;

      .agree {
        width: 140px;
        height: 44px;
        background: #ff7a1f;
        border-radius: 5px;
        text-align: center;
        line-height: 44px;
      }

      .cancle {
        width: 140px;
        height: 44px;
        background: #85898c;
        border-radius: 5px;
        text-align: center;
        line-height: 44px;
      }
    }
  }
}
</style>
